import os
import shutil
import pyflag.DB as DB
import pyflag.Reports as Reports
import pyflag.FileSystem as FileSystem


class ScanReport(Reports.report):
    parameters = {'destdir':'any', 'final':'string'}
    name = "Export files"
    family = "Hash Analysis"
    description = "Generate report and export files"
    order = 100


    def form(self, query, result):
	result.fileselector("Select output directory for copy files", 'destdir', True)
	result.checkbox("Click here when finished", 'final', 'ok')
	return result
			    
			    
    def display(self, query, result):
	result.heading("Export finished")
	result.text("Copy files and reports are in directory: %s" % query['destdir'])
	return result
	

    def progress(self, query, result):
	result.heading("Please wait")
	result.text("Copying files...")
	return result
    
	
    def analyse(self, query):
        self.destdir = query['destdir']
        
        if self.destdir[-1] != '/':
            self.destdir += "/"
            
        self.__makeDir(self.destdir)            
    	self.dbh = DB.DBO(query['case'])
    	
    	# Copy and create reports for UKN FILES
    	uknName = 'Unknown'
    	sqlQuery = 'SELECT f.inode, concat(f.path, f.name) as file, ukn.md5, ukn.sha1, i.mtime, i.atime, i.ctime FROM file AS f \
    	    INNER JOIN inode AS i ON f.inode_id = i.inode_id \
    	    INNER JOIN unknownfiles AS ukn ON i.inode_id = ukn.inode_id \
    	    ORDER BY file'
        self.__copyFiles(query, self.destdir + uknName, sqlQuery)
        self.__HTMLReport(uknName, sqlQuery)
        self.__CSVReport(uknName, sqlQuery)
        
        # Copy and create reports for WNT FILES
        wntName = 'Wanted'
        sqlQuery = 'SELECT f.inode, concat(f.path, f.name) as file, wnt.md5hash AS md5, wnt.sha1hash AS sha1, i.mtime, i.atime, i.ctime FROM file AS f \
    	    INNER JOIN inode AS i ON f.inode_id = i.inode_id \
    	    INNER JOIN wantedfiles AS wnt ON i.inode_id = wnt.inode_id \
    	    ORDER BY file'
    	self.__copyFiles(query, self.destdir + wntName, sqlQuery)
        self.__HTMLReport(wntName, sqlQuery)
        self.__CSVReport(wntName, sqlQuery)


            
    def __CSVReport(self, reportName, query):
	self.dbh.execute(query)
	import csv
	writer = csv.writer(open(self.destdir + reportName + '.xls', 'w'), 'excel')
	writer.writerow(['file', 'md5', 'sha1', 'mtime', 'atime', 'ctime'])
	
	while True:
	    result = self.dbh.fetch()
	    if not result: break
	    writer.writerow([result['file'], result['md5'], result['sha1'], result['mtime'], result['atime'], result['ctime']])



    def __HTMLReport(self, reportName, query):
	self.dbh.execute(query)
	htmlfile = open(self.destdir + reportName + '.html', 'w')
	count = 0

        # Set html style
	htmlfile.write("<style>\n")
        content = "#table-style {\n \
		\tborder: 1px solid black;\n \
		\twidth: 100%;\n \
		\tspacing: 20;\n \
		\tpadding: 10;\n \
		}\n#table-style td {\n \
		\tfont-family: Tahoma;\n \
		\tfont-size: 10pt;\n \
		}\n"
        htmlfile.write(content)
        htmlfile.write("</style>\n")
	htmlfile.write("<html>")
	htmlfile.write("<h1>%s</h1>" % (reportName + ' files'))
	htmlfile.write("<table id=\"table-style\">\n")
	htmlfile.write("\t<tr><th>File</th><th>md5</th><th>sha1</th><th>mtime</th><th>atime</th><th>ctime</th></tr>\n")
	
	while True:
	    result = self.dbh.fetch()
	    if not result: break
	    data = [result['file'], result['md5'], result['sha1'], result['mtime'], result['atime'], result['ctime']]
	    count += 1
	    
	    if count % 2 == 0: bgcolor = "#FFFFFF"
	    else: bgcolor = "#EEEFFF"
	    
	    tr = "\t<tr bgcolor=\"%s\">" % bgcolor
	    
	    for i in range(len(data)):
		if i == 0:
		    path = os.path.dirname(data[i])
		    tr += "<td><a href=\"./%s%s\">%s</a></td>" % (reportName, path, data[i])
		else:
		    tr += "<td>%s</td>" % data[i]
	    
	    tr += "</tr>\n"
	    htmlfile.write(tr)

	htmlfile.write("</table>")
	htmlfile.write("</html>\n")
	htmlfile.close()
	


    # Copy files
    def __copyFiles(self, query, outputDir, sqlQuery):
	self.dbh.execute(sqlQuery)
	self.__makeDir(outputDir)
	    
	while True:
	    result = self.dbh.fetch()
	    if not result: break
		
	    inode = result['inode']
	    fullpath = outputDir + result['file']
	    self.__makeDir(os.path.dirname(fullpath))		
	    fsfd = FileSystem.DBFS(query['case'])
	    fd = fsfd.open(inode = inode)
		
	    try:
		self.__cp(fd.fd.name, fullpath)
	    except Exception, e:
		pass

	
    # Create new directory if not exist
    # path - path new directory
    def __makeDir(self, path):
	try:
	    os.makedirs(path)
	except Exception, e:
	    pass

    
    # Copy file src to dest directory
    def __cp(self, src, dest):
	try:
	    shutil.copy(src, dest);
	except Exception, e:
	    pass
